package com.fs.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.fs.common.constant.CacheConstants;
import com.fs.common.constant.UserConstants;
import com.fs.common.core.pojo.SysUser;
import com.fs.common.exception.ServiceException;
import com.fs.common.exception.user.*;
import com.fs.common.util.RedisCache;
import com.fs.common.util.ip.IpUtils;
import com.fs.common.util.sign.PasswordUtils;
import com.fs.system.service.ISysConfigService;
import com.fs.system.service.ISysLoginService;
import com.fs.system.service.ISysRegisterService;
import com.fs.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
@Service
public class SysRegisterService implements ISysRegisterService {
    @Autowired
    ISysConfigService configService;
    @Autowired
    RedisCache redisCache;
    @Autowired
    ISysUserService sysUserService;
    @Autowired
    ISysLoginService loginService;

    @Override
    public void register(String userName, String password,String code, String uuid) {
        loginService.validateCaptcha(code,uuid);
        loginPreCheck(userName,password);
        SysUser user=sysUserService.selectUserByName(userName);
        if(Objects.isNull(user)){
            user=new SysUser();
            user.setUserName(userName);
            user.setNickName(userName);
            password= PasswordUtils.generate(password);
            user.setPassword(password);
            sysUserService.insertUser(user);
        }else{
            throw new ServiceException("该用户已存在");
        }
    }


    public void loginPreCheck(String username, String password){
        //检测用户名/密码是否为空
        if(StrUtil.isEmpty(username)||StrUtil.isEmpty(password)){
            throw new UserNotExistsException();
        }
        //检测用户名的长度
        if(username.length()> UserConstants.USERNAME_MAX_LENGTH || username.length()<UserConstants.USERNAME_MIN_LENGTH){
            throw new UserPasswordNotMatchException();
        }
        //检测密码的长度
        if(password.length()> UserConstants.PASSWORD_MAX_LENGTH || password.length()<UserConstants.PASSWORD_MIN_LENGTH){
            throw new UserPasswordNotMatchException();
        }

    }
}
